﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using asMeishi.web.Models;
using publicLibrary;

using MongoDB.Bson;

namespace asMeishi.web.Controllers
{
    using Classes;
    public class commentController : Controller
    {
        //
        // GET: /comment/

        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Index(string shopName,string content,string shopId,int id=1)
        {
            

            DataSession<MongoDataContext, comment> db = new DataSession<MongoDataContext, comment>();
            IQueryable<comment> cs = db.query;
            if(!String.IsNullOrWhiteSpace(shopName)){
                shop s = new shopC().getByName(shopName);
                if (s != null) {
                    cs = cs.Where(d => d.targetId == s.Id); 
                }
            }

            if (!String.IsNullOrWhiteSpace(content))
            {
                cs = cs.Where(d => d.content.Contains(content) );
            }

            if (!string.IsNullOrWhiteSpace(shopId)) {
                ObjectId oid = shopId.toOId();
                cs = cs.Where(d => d.targetId == oid); 
                
            }

            
            paging<comment> paging = new paging<comment>(cs, 20);
            ViewData.Model = paging.content(id).ToList();
            ViewBag.pageInfo = paging.info();

            return View();
        }

        //
        // GET: /comment/Details/5

        public ActionResult Detail(int id)
        {
            return View();
        }

        //
        // GET: /comment/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /comment/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /comment/Edit/5
 
        public ActionResult Edit(string id)
        {
            commentC cc = new commentC();
            
            return View(cc.get(id));
        }

        //
        // POST: /comment/Edit/5

        [HttpPost]
        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Edit(string id, FormCollection collection)
        {
            comment comment = new comment();

            try
            {
                commentC cc = new commentC();
                if (!string.IsNullOrWhiteSpace(id)) comment = cc.get(id);
                TryUpdateModel(comment);
                
                cc.save(comment);

                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }


        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Delete(string id)
        {
            try
            {
                // TODO: Add delete logic here

                commentC cc = new commentC();
                cc.del(id);

                 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //*************************
        //************Ajax********************
        //***********************
        /// <summary>
        /// Ajax请求，并在user 取出userName
        /// </summary>
        
        [OutputCache(Duration=30)]
        public ActionResult get(string id,string start,string end)
        {

            commentC cc = new commentC();
            var data = cc.getByShopId(id.toOId()).OrderByDescending(d => d.datetime);
            var _jd = data.Skip(Convert.ToInt32(start)).Take(Convert.ToInt32(end)).Select(d=>
                new {
                    Id=d.Id.ToString(),
                    d.content,
                    d.cost,
                    d.datetime,
                    d.priceQuality,
                    d.food,
                    d.quality,
                    d.service,
                    userId=d.userId.ToString(),
                    d.userName
                }
                ).ToList().AsEnumerable();

            return json(_jd);

        }

        [HttpPost]
        public ActionResult add(string id, FormCollection collection)
        {
            try
            {
                string shopId = id;
                commentC cC = new commentC();
                comment comment = cC.createDefault(userC.loginUser);
                //写入comment
                TryUpdateModel(comment);
                comment.targetId = shopId.toOId();
                comment.datetime = DateTime.Now;
                //有些多余．暂时保留．后期可能把items字段改成[]
                cC.updateFood(ref comment, collection.Get("itemNames"));
                cC.save(comment);
                var Id = comment.Id.ToString();


                shopC sc = new shopC();
                shop shop = sc.getById(shopId);

                //写入菜表
                if (!string.IsNullOrWhiteSpace(comment.food))
                {
                    foodC iC = new foodC();
                    List<food> items = iC.addstr(comment.food, shopId.toOId(), userC.loginUser);

                    //菜写入shop表
                    sc.updataFood(ref shop, items, userC.loginUser);

                }
                //来至shop的动作，对shop进行合算分，对comment中的分处理

                sc.updataComment(ref shop, comment.cost, comment.quality, comment.service, comment.priceQuality);
                sc.save(shop);

            }catch(Exception e){
             return Content(AjaxCallBackInfo.jsonError(e.Message));
            }


            return Content(AjaxCallBackInfo.jsonOk());
        }

        private ActionResult json(object obj)
        {
            return Json(obj, JsonRequestBehavior.AllowGet);
            //return base.Content(obj.ToJSON());
        }
    }


}
